import { Component, OnInit } from '@angular/core';
import { ConfigService } from './service/config.service';
import { CodeService } from './service/code.service'
import { Template } from '../../app/template'
import { IpcClient } from './core/IpcClient'
import { Future } from './util/future'
import { NgForm } from '@angular/forms'
import { tap } from 'rxjs/operators'
import { MatSnackBar } from '@angular/material/snack-bar'

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
    public checkDbTask: Future<string[]>
    public generateTask: Future<any>

    public templates: Array<Template> = []
    public selectedTemplate: Template

    constructor(private snackBar: MatSnackBar, public codeService: CodeService, public config: ConfigService, public ipcClient: IpcClient) {
    }

    ngOnInit(): void {
        this.codeService.getTemplates().subscribe(value => {
            this.templates = value
        })
    }

    log(element: any) {
        console.log(element);
    }

    settings() {
    }

    openDirectory() {
        this.ipcClient.openDirectory().subscribe(value => {
            if (!value.canceled) {
                this.config.projectRoot = value.filePaths[0]
            }
        })
    }

    isEnabled(dbForm: NgForm, projectForm: NgForm) {
        return !(dbForm.invalid || projectForm.invalid || !this.selectedTemplate)
            && (!this.generateTask || this.generateTask.isDone);
    }

    checkDb(form: NgForm) {
        console.log(1)
        console.log(form, form.valid)
        if (form.valid && (!this.checkDbTask || this.checkDbTask.isDone)) {
            console.log(2)
            console.log(form.value)
            this.checkDbTask = new Future<string[]>(this.codeService.checkDb(form.value))
        }
    }

    generate(dbForm: NgForm, projectForm: NgForm) {
        if (dbForm.valid && projectForm.valid && this.selectedTemplate
            && (!this.checkDbTask || this.checkDbTask.isDone)) {
            const config = {...this.config}
            const template = this.selectedTemplate

            this.generateTask = new Future<any>(
                this.codeService.generateCode(template, config).pipe(tap(x => {
                    if (x) {
                        this.snackBar.open('操作成功', null, {duration: 5000})
                    }
                }))
            )
        }
    }
}
